package com.srwl.mytx.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.alibaba.fastjson.JSONObject;

import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.dao.DBManager;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Recharge;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.service.AliService;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.utils.DateUtils;
import com.srwl.mytx.utils.Utils;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 充值详情页面
 * <p>
 * 后端异步验签能获取用户支付的支付宝账户后，应该把支付账户也显示到该页面
 */
public class RechargeDetailActivity extends BaseActivity {
    private static final String TAG = "RechargeDetailActivity";

    public static void startActivity(Context context, String rechargeId) {

        context.startActivity(new Intent(context, RechargeDetailActivity.class).putExtra("rechargeId", rechargeId));
    }

    @BindView(R.id.tv_amount)
    TextView tv_amount;
    @BindView(R.id.tv_amount_tips)
    TextView tv_amountTips;
    @BindView(R.id.tv_recharge_channel)
    TextView tv_rechargeChannel;
    @BindView(R.id.tv_channel_order_id)
    TextView tv_channelOrderId;
    @BindView(R.id.tv_recharge_id)
    TextView tv_rechargeId;
    @BindView(R.id.tv_created)
    TextView tv_created;
    @BindView(R.id.tv_customer_service)
    TextView tv_customerService;
    @BindView(R.id.progress_bar)
    ProgressBar progressBar;


    private String rechargeId;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recharge_detail);
        ButterKnife.bind(this);
        rechargeId = getIntent().getStringExtra("rechargeId");
        loadData();
        tv_customerService.setOnClickListener(v -> contactCustomerService());
    }

    private void loadData() {
        if (!Helper.getInstance().isNetworkConnected()) {
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(AliService.class)
                .getRecharge(rechargeId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult body = response.body();
                        if (!response.isSuccessful() || body == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            return;
                        }

                        if (body.isError()) {
                            Log.e(TAG, "onResponse: " + body.getMsg());
                            return;
                        }

                        Object data = body.getData();
                        if (data != null) {
                            JSONObject jsonObject = (JSONObject) data;
                            Recharge recharge = jsonObject.toJavaObject(Recharge.class);
                            setupViews(recharge);

                        }

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        t.printStackTrace();
                    }
                });
    }

    private void setupViews(Recharge recharge) {
        tv_amount.setText(Utils.moneyFormat(recharge.getAmount()));
        Integer status = recharge.getStatus();
        if (status != null) {
            switch (status) {
                case Constant.RECHARGE_STATUS_INIT:
                    tv_amountTips.setText("未支付");
                    break;

                case Constant.RECHARGE_STATUS_SUCCESS:
                    tv_amountTips.setText("充值成功");
                    break;

                case Constant.RECHARGE_STATUS_ERROR:
                    tv_amountTips.setText("充值失败");
                    break;
                default:
                    tv_amountTips.setText("异常订单");
            }
        } else {
            tv_amountTips.setText("异常订单");
        }

        tv_channelOrderId.setText(recharge.getTradeNo());
        tv_rechargeId.setText(recharge.getId());
        tv_created.setText(DateUtils.dateToString(recharge.getGmtPayment(), DateUtils.FORMAT_TIMESTAMP));
    }


    /**
     * 联系客服
     */
    void contactCustomerService() {
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(UserService.class)
                .customerService()
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(tv_customerService, getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.d(TAG, "onResponse: " + result.getMsg());
                            return;
                        }

                        JSONObject object = (JSONObject) result.getData();
                        //把用户作为临时联系人 保存在数据库
                        User manualUser = object.toJavaObject(User.class);
                        manualUser.setType(Constant.USER_TYPE_TEMP);
                        DBManager.getInstance().getDaoSession().getUserDao().insertOrReplace(manualUser);
                        ChatActivity.startActivity(RechargeDetailActivity.this, manualUser);

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        showToast(tv_customerService, getString(R.string.system_busy));
                    }
                });
    }

}